package com.IceCreamQAQ.test.controller;

import act.controller.Controller;
import com.IceCreamQAQ.test.entity.User;
import com.IceCreamQAQ.test.service.UserService;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.result.Result;

import javax.inject.Inject;

public class UserController extends Controller.Util {

    @Inject
    private UserService service;

    @GetAction("register")
    public void register() {

    }

    @GetAction("login")
    public void login() {

    }

    @PostAction("doRegister")
    public Result doRegister(User user) {
        try{
            user.password=User.getPasswordHash(user.password);
            service.register(user);
        }catch (Exception e){
            e.printStackTrace();
            return renderHtml("<script>alert('\\u6CE8\\u518C\\u5931\\u8D25\\uFF01');window.history.back();</script>");
        }
        return renderHtml("<script>alert('\\u6CE8\\u518C\\u6210\\u529F\\uFF01uid:"+user.id+"');location.href='login';</script>");
    }

    @PostAction("doLogin")
    public Result doLogin(Integer uid,String pwd) {
        try{
            User user=service.login(uid,pwd);
            if (user!=null)return renderHtml("<script>alert('\\u767B\\u5F55\\u6210\\u529F\\uFF01');location.href='register';</script>");
            return renderHtml("<script>alert('\\u767B\\u5F55\\u5931\\u8D25\\uFF01');window.history.back();</script>");
        }catch (Exception e){
            e.printStackTrace();
            return renderHtml("<script>alert('\\u767B\\u5F55\\u5931\\u8D25\\uFF01');window.history.back();</script>");
        }
    }
}
